package demo3;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Map;

@Controller
public class ParamCtl {
    @RequestMapping("/generalParam")
    public String general(HttpServletRequest req, HttpServletResponse resp, HttpSession session,Model m,Map map){
        req.setAttribute("name","李老师");
        session.setAttribute("age",20);
        m.addAttribute("phone","139");//等同于req.setAttribute
        return "general";//转发
        //return "redirect:/general";
    }

    @PostMapping("/simple")
    public String simple(String name, @RequestParam(name="a",defaultValue = "23") int age, Boolean ok, String[]hobbies){
        System.out.println("name:"+name+",age:"+age+",ok:"+ok);
        System.out.println(Arrays.toString(hobbies));
        return "simple";
    }

    @RequestMapping(value="/user")
    @ResponseBody
    public User userInfo(User u,Model m){
        System.out.println(u.getHobbies());
        //u.setHobbies(null);
        System.out.println("birth:" + u.getBirth());

//User对象会自动放入model中，key为对象的类型"user"
        m.addAttribute("hello", "123");
        System.out.println("model="+m);
        u.setName((String)m.getAttribute("userName"));
        //u.setAddr((Address)m.getAttribute("addr"));
        return u;
    }

    @ModelAttribute//优先于所有方法，被执行
    public void initMode1(Model m){
        m.addAttribute("userName","菩提本无树，明镜亦非台");
    }

    @ModelAttribute("addr")
    public Address init2(){
        Address a=new Address();
        a.setCity("北京");
        return a;
    }
}
